#define _CRT_SECURE_NO_WARNINGS 1

#include "binaryTree.h"
#include "queue.h"

BTNode* BinaryTreeCreate(BTDataType* a, int n, int* pi)
{
	BTNode* node = (BTNode*)malloc(sizeof(BTNode));
	if (node == NULL)
	{
		perror("node malloc");
	}

	if (a[(*pi)] == '#')
	{
		(*pi)++;
		return NULL;
	}

	node->data = a[(*pi)++];
	node->left = BinaryTreeCreate(a, n, pi);
	node->right = BinaryTreeCreate(a, n, pi);

	return node;
}

void BinaryTreeDestory(BTNode** root)
{
	if (*root == NULL)
		return;
	
	BinaryTreeDestory(&((*root)->left));
	BinaryTreeDestory(&((*root)->right));

	BTNode* cur = *root;
	free(cur);
	cur = NULL;

	return;
}

int BinaryTreeSize(BTNode* root)
{
	if (root == NULL)
		return 0;

	return BinaryTreeSize(root->left) + BinaryTreeSize(root->right) + 1;
}

int BinaryTreeLeafSize(BTNode* root)
{
	if (root == NULL)
		return 0;

	if (root->left == NULL && root->right == NULL)
		return 1;

	return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);

}

int BinaryTreeLevelKSize(BTNode* root, int k)
{
	if (root == NULL)
		return 0;

	if (k == 1)
		return 1;

	return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
}

BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
{
	if (root == NULL)
		return NULL;

	if (root->data == x)
		return root;

	BTNode* lfind = BinaryTreeFind(root->left, x);
	if (lfind)
		return lfind;
	BTNode* rfind = BinaryTreeFind(root->right, x);
	if (rfind)
		return rfind;

	return NULL;
}

void BinaryTreePrevOrder(BTNode* root)
{
	if (root == NULL)
		return;

	printf("%c ", root->data);
	BinaryTreePrevOrder(root->left);
	BinaryTreePrevOrder(root->right);
}

void BinaryTreeInOrder(BTNode* root)
{
	if (root == NULL)
		return;

	BinaryTreePrevOrder(root->left);
	printf("%c ", root->data);
	BinaryTreePrevOrder(root->right);
}

void BinaryTreePostOrder(BTNode* root)
{
	if (root == NULL)
		return;

	BinaryTreePrevOrder(root->left);
	BinaryTreePrevOrder(root->right);
	printf("%c ", root->data);
}

void BinaryTreeLevelOrder(BTNode* root)
{
	Queue q;
	QInit(&q);

	if (root)
		QPush(&q, root);

	while (!QEmpty(&q))
	{
		BTNode* front = QFront(&q);
		QPop(&q);
		printf("%c ", front->data);
		
		if (front->left)
			QPush(&q, front->left);

		if (front->right)
			QPush(&q, front->right);
	}

	QDestroy(&q);
}
